import {Component,OnInit,ChangeDetectorRef} from '@angular/core';
import { LoginInfoService } from '../../../services/login-info.service';
import { Router } from '@angular/router';
import { commService } from '../../../services/comm.service';
import { ActionSheetController } from '@ionic/angular';
import { UpphotoService } from '../../../services/upphoto.service';
import { HttpService } from '../../../services/http.service';
import { BaseUiService } from '../../../services/base-ui.service';
import {EventService  } from '../../../services/QaService';
declare var AlloyCrop;
@Component({
  selector: 'app-verified',
  templateUrl: './verified.page.html',
  styleUrls: ['./verified.page.scss'],
})
export class VerifiedPage implements OnInit {
  public userInfo:any={};
  public birthday:any={};
  public gender:any={};
  public cropPicture = '';
  public zhengImg = '../../../assets/image/verified_zheng.png';
  public fanImg = '../../../assets/image/verified_fan.png';
  public isShi = false;
  public identity=[];
  
  public idInfo = {
    idCard:"",
    name:""
  };

  public operation="1";
  public isShowInfo = false;
  constructor(
    public BaseUiService: BaseUiService,
    public HttpService: HttpService,
    public commService: commService,
    public router: Router,
    public LoginInfoService:LoginInfoService,
    public upphotoService:UpphotoService,
    public eventService:EventService,
    public actionSheetController: ActionSheetController,
    private cd: ChangeDetectorRef
  ) { 
    this.userInfo = this.LoginInfoService.getlocal('user');

    console.log("----verified---",this.userInfo)
    this.searchIdentCart();
    this.userInfo.idCard==""?"0":"1";
  }

  ngOnInit() {
  
  }

  //底部弹出
  async presentActionSheet(idx) {
      const actionSheet = await this.actionSheetController.create({
        header: '上传头像',
        buttons: [ {
          text: '拍照上传',
          icon: 'camera',
          handler: () => {
            if(idx == 1){
              this.commService.collectIDCardFront().subscribe(res=>{
                this.demo(res,idx);
              })
            }else {
              this.commService.collectIDCardBack().subscribe(res=>{
                this.demo(res,idx);
              })
            }
            
          }
        }, {
          text: '相册上传',
          icon: 'image-outline',
          handler: () => {
            this.commService.picture(300,40).subscribe(res =>{
              this.demo(res,idx);
            })
          }
        }, {
          text: '关闭',
          icon: 'close',
          role: 'cancel',
          handler: () => {
            console.log('关闭');
          }
        }]
      });
      await actionSheet.present();
  }

  demo(info:any,idx:any){
    let _this =this
    this.upphotoService.Uploading(info).then( res1 =>{
      if(idx == 1){
        console.log('----------operation--------------')
        _this.zhengImg = res1[0]['filePath'];
        console.log(_this.operation)
        _this.HttpService.verified({filepath: _this.zhengImg,userId: this.userInfo.unitGuid,type: 1}).then(
          res => {
            console.log(res['item'].map);
            if(res["code"]=="500" || !!!res['item'].map){
                this.BaseUiService.showToast("身份证读取失败，请重新上传",'customred','top')
                return false;
            }
            console.log('-----------' + JSON.stringify(res))
            _this.idInfo = res['item'].map;
           
            _this.isShowInfo = true;
            console.log(this.isShowInfo)
            this.cd.detectChanges();
          }
        )
      }else {
        this.fanImg = res1[0]['filePath'];
        _this.HttpService.verified({filepath: _this.zhengImg,userId: this.userInfo.unitGuid,type: 2}).then(
          res => {
            
          }
        )
      }
      this.cd.detectChanges();
    })
  }

  submit(){
    if(!this.zhengImg || !this.fanImg){
      this.BaseUiService.showToast('请先上传照片','danger','top');
      return;
    }

    if(!this.idInfo['name'] || ! this.idInfo['idCard']){
      this.BaseUiService.showToast('识别失败，请重新上传身份证','danger','top');
      return;
    }
    let year = this.idInfo['birth'].substr(0, 4);
    let month = this.idInfo['birth'].substr(4, 2);
    let day = this.idInfo['birth'].substr(6, 2);
    let birthday = year + "-" + month + "-" + day;
    let info = {
      unitGuid: this.userInfo.unitGuid,
      userName: this.idInfo['name'],
      idCard: this.idInfo['idCard'],
      gender: this.idInfo['sex'] == '男' ? 1 : 0,
      birthday: birthday,
      iDCardImg:this.zhengImg+","+this.fanImg, 
      address: this.idInfo['address'],
      registeAddress: this.idInfo['address']
    }
    this.HttpService.xgheadphoto(info).then(
      res => {
        this.userInfo.userName = this.idInfo['name'];
        this.userInfo.idCard = this.idInfo['idCard'];
        this.userInfo.gender = this.idInfo['sex'] == '男' ? 1 : 0;
        this.userInfo.birthday = birthday;
        this.userInfo.address = this.idInfo['address'];
        this.userInfo.registeAddress = this.idInfo['address'];
        // this.LoginInfoService.setInfo({user: this.userInfo});
       let merryObject= Object.assign(this.LoginInfoService.getInfo(),this.userInfo)
       console.log("----merryObject----",merryObject)
       this.LoginInfoService.setlocal('user',merryObject) ;
        this.eventService.eventEmitter.emit('loginEvent');
        this.BaseUiService.showToast('修改成功','success','top');
        setTimeout(()=>{
          history.go(-1);
        },1000)
        
      }
    )
  }

  //根据身份证号截取生日
  getInfoByIdNo(UUserCard){
    let id = UUserCard.toString() 
    //获取出生日期
    this.birthday = id.substring(6, 10) + "-" + id.substring(10, 12) + "-" + id.substring(12, 14);
    //获取性别
    if (parseInt(id.substr(16, 1)) % 2 == 1) {
      //男
      this.gender =  1;
    } else {
      //女
      this.gender = 0;
    }
  }

  /**
   * @memberOf VerifiedPage
   * @description 查看身份证存件信息
   */
  searchIdentCart(){
    let params={
      userId: this.userInfo.unitGuid
    }
    this.HttpService.iDCardImg(params).then( res1 =>{
      console.log(res1)
      if(res1['code']=="200" && res1['items'].length!=0){
        this.isShi = true;
        this.zhengImg=res1["items"][0]
        this.fanImg=res1["items"][1]
      }
    })

  }

  
}
